package com.aso114.project.mvp.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.aso114.project.R;
import com.aso114.project.base.BaseSimpleActivity;
import com.aso114.project.bean.OrderStaus;
import com.aso114.project.mvp.alipay.H5PayDemoActivity;
import com.aso114.project.mvp.model.CallBack;
import com.aso114.project.mvp.model.CommentModel;
import com.aso114.project.util.ActivityCollector;
import com.aso114.project.util.Helper;
import com.aso114.project.util.WxpayUtils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;

public class WxPayOrderActivity extends BaseSimpleActivity {
    String orderNo = "";
    String date1, date2 = "";
    Intent intent = new Intent(MainActivity.REFRESH);
    int type = 0;//0表示第一次进来 不需要请求订单是否支付状态   1  表示要请求
    @BindView(R.id.layout_title_bar_back_iv)
    ImageView layoutTitleBarBackIv;
    @BindView(R.id.layout_title_bar_title_tv)
    TextView layoutTitleBarTitleTv;
    Message msg = new Message();
    Timer timer ;
    @Override
    protected int getResouseId() {
        return R.layout.wxpay_layout;
    }

    @Override
    protected void initView() {
        layoutTitleBarTitleTv.setText("请求支付");
        // 获取当前时间
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        date1 = formatter.format(currentTime);
        System.out.println("当前时间====" + date1);
        orderNo = getIntent().getStringExtra("orderNo");

        new Thread(networkTask).start();


        layoutTitleBarBackIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                msg.what = Integer.valueOf(1);//1是失败 2是成功
                mHandler.sendMessage(msg); // 向Handler发送消息,更新UI
            }
        });

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            System.out.println("按下了back键   onKeyDown()");

            msg.what = Integer.valueOf(1);//1是失败 2是成功
            mHandler.sendMessage(msg); // 向Handler发送消息,更新UI
            return false;
        }else {
            return super.onKeyDown(keyCode, event);
        }

    }



    @Override
    protected void onResume() {
        super.onResume();

        if (type == 0) {


            type = 1;
            return;
        } else if (type == 1) {

            timer = new Timer();
            timer.schedule(new TimerTask() {
                public void run() {
                    System.out.println("Time's up!");
                    //计算是否超过1分钟


                    if ((int) gettime() >= 60) {

                        msg.what = Integer.valueOf(1);//1是失败 2是成功

                        mHandler.sendMessage(msg); // 向Handler发送消息,更新UI

                    } else {

//                        Message msg = new Message();
//                        msg.what = Integer.valueOf(2);//1是失败 2是成功
//
//                        mHandler.sendMessage(msg); // 向Handler发送消息,更新UI
                        getdata(orderNo);
                    }


//
                }
            }, 0, 3000);

        }

    }


    @Override
    protected void onPause() {
        super.onPause();
        if (timer != null) {
            timer.cancel();
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        type = 0;
        if (timer != null) {
            timer.cancel();
        }
    }


    private Handler mHandler = new Handler() {

        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    gotoactivity("1");//1是失败 2是成功
                    break;
                case 2:
                    gotoactivity("2");//1是失败 2是成功
                    break;

            }
        }

        ;
    };


    private void gotoactivity(final String type) {

        //充值成功就是会员
        if(type.equals("2")){
//            intent = new Intent(WxPayOrderActivity.this, VipCoreActivity.class);
//            intent.putExtra("vipTpye","1");
//            startActivity(intent);

            if(OpenVipActivity.instance!=null){
                OpenVipActivity.instance.finish();
            }

            finish();
        }else{
            //充值失败，则判断之前是否会员
            //这边需要加个 判断之前是否是会员
//            intent = new Intent(WxPayOrderActivity.this, VipCoreActivity.class);
//            intent.putExtra("vipTpye","0");
//            startActivity(intent);

            finish();
        }
    }

    public void getdata(String orderno) {


        CommentModel.getInstant().getWxPayOrder(orderno, new CallBack() {
            @Override
            public void onSuccess(Object o, boolean isSuccess, String msg) {
                Helper.gotoLogin(isSuccess);//token失效去重新登陆
                OrderStaus order = (OrderStaus) o;
                if (order == null) {
                    return;
                }

                if (order.getOrderStatus().equals("3")) {
                    Message msg1 = new Message();
                    msg1.what = Integer.valueOf(2);//1是失败 2是成功

                    mHandler.sendMessage(msg1); // 向Handler发送消息,更新UI
                } else {
                    Log.e("llx", "支付失败===");

                }
                Log.e("llx", order.getOrderNo() + "===" + order.getOrderStatus());

            }

            @Override
            public void onFailure(String fail) {

            }

        });

    }


    public long gettime() {

        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        date2 = formatter.format(currentTime);

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        System.out.println("答完答题时间123====" + date2);
        long second = 0;
        try {
            Date d1 = df.parse(date1);
            Date d2 = df.parse(date2);
            long diff = d2.getTime() - d1.getTime();// 这样得到的差值是微秒级别


            long days = diff / (1000 * 60 * 60 * 24);
            long hours = (diff - days * (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
            second = (diff - days * (1000 * 60 * 60 * 24) - hours * (1000 * 60 * 60)) / (1000);
            System.out.println("间隔时间====" + second + "秒");

        } catch (Exception e) {
        }

        return second;
    }


    /**
     * 网络操作相关的子线程
     */
    Runnable networkTask = new Runnable() {

        @Override
        public void run() {
            // TODO
            // 在这里进行 http request.网络请求相关操作
            WxpayUtils.payorder(WxPayOrderActivity.this, orderNo);
        }
    };

    @Override
    protected void initData() {

    }

    @Override
    protected void getBroadcast(Context context, Intent intent) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
